<?php

namespace Ysy\HyperfImport\Importer\Driver;

use Generator;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class ExcelDriver implements DriverInterface
{
    public function read(
        string $filePath,
        string $extension,
        bool $skipHeader = true,
        array $options = [],
        int &$totalCount = 0
    ): Generator {
        try {
            // 从options提取Excel专属配置（无类属性）
            $readAllSheets = $options['read_all_sheets'] ?? true;

            // 初始化读取器（每次读取新实例）
            $reader = match ($extension) {
                'xlsx' => new Xlsx(),
                'xls' => new Xls(),
                default => throw new \RuntimeException("不支持的Excel格式：{$extension}")
            };
            $reader->setReadDataOnly(true); // 减少内存占用

            $spreadsheet = $reader->load($filePath);
            $sheets = $spreadsheet->getAllSheets();
            $totalCount = 0; // 每次读取重置计数

            foreach ($sheets as $sheetIndex => $worksheet) {
                $sheetName = $worksheet->getTitle();
                $rowIterator = $worksheet->getRowIterator();
                $header = [];
                $rowIndex = 0;

                foreach ($rowIterator as $row) {
                    $rowIndex++;
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(false);

                    $rowData = [];
                    $colIndex = 0;
                    foreach ($cellIterator as $cell) {
                        $value = $cell->getValue();
                        // 日期格式处理
                        if (is_numeric($value) && Date::isDateTime($cell)) {
                            $value = Date::excelToDateTimeObject($value)->format('Y-m-d H:i:s');
                        }
                        $rowData[$colIndex] = $value;
                        $colIndex++;
                    }

                    // 表头处理
                    if ($skipHeader && $rowIndex === 1) {
                        $header = $rowData;
                        continue;
                    }
                    // 表头映射
                    if ($skipHeader && !empty($header)) {
                        $rowData = array_combine($header, $rowData) ?: $rowData;
                    }

                    // 计数+返回数据（与CSV格式对齐）
                    $totalCount++;
                    yield [
                        'sheet_name' => $sheetName,
                        'row_index' => $rowIndex,
                        'data' => $rowData,
                        'current_count' => $totalCount
                    ];
                }

                // 控制是否只读第一个sheet
                if (!$readAllSheets) {
                    break;
                }
            }

            // 释放内存
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);

        } catch (\Exception $e) {
            throw new \RuntimeException("Excel读取失败：{$e->getMessage()}");
        }
    }
}